<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="./style.css">
  <script src="./data.js"></script>
</head>
<body>
  <div class="exam">
    <div class="header">
      <div class="progress">
        <div class="line">
          <span>0%</span>
          <b></b>
        </div>
        <p>当前第<span class="current"></span>题/共<span class="total"></span>题</p>
      </div>
      <div class="count-down">
        <button class="timer-btn">开始</button>
        <span></span>
      </div>
    </div>
    <div class="title">单选题</div>
    <div class="question">
      <h3></h3>
      <ul></ul>
      <div class="question-btm">
        <span>收藏本题</span>
        <div class="btns">
          <button class="submit">提交试卷</button>
          <button class="next">下一题</button>
        </div>
      </div>
    </div>
    <div class="card">
      <div class="toggle close">展示答题卡</div>
      <div class="pages"></div>
    </div>
    <div class="totalNum"></div>
  </div>

  <script>
    const $ = el => document.querySelector(el)
    const $all = el => [...document.querySelectorAll(el)]
    // 当前选中题目的下标
    let currentIndex = 0
    const letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G']

    function init() {
      $('.total').innerHTML = QuestionJosn.length
      $('.pages').innerHTML = QuestionJosn.map((item, index) => {
        return `<button>${index + 1}</button>`
      }).join('')

      renderQuestion()
      bindEvent()
    }
    init()

    // 渲染题目
    function renderQuestion() {
      const { questionTitle, questionItems, myAnswer } = QuestionJosn[currentIndex]
      $('.current').innerHTML = currentIndex + 1
      $('.question h3').innerHTML = questionTitle
      $('.question ul').innerHTML = questionItems.split(';').map((it, index) => {
        const id = 'q' + currentIndex + index
        const checked = myAnswer === it ? 'checked' : ''
        return `
          <li>
            <input type="radio" name="1" id="${id}" value="${letters[index]}" ${checked}>
            <label for="${id}">${letters[index]}. ${it}</label>
          </li>
        `
      }).join('')
      $('.pages .active-btn')?.classList.remove('active-btn')
      $all('.pages button')[currentIndex].classList.add('active-btn', 'border')

      bindChange()
    }

    function bindEvent() {
      // 下一页
      $('.next').addEventListener('click', () => {
        if (currentIndex === QuestionJosn.length - 1) {
          return alert('已经是最后一道题了')
        }
        currentIndex++
        renderQuestion()
      })
      // 题目按钮
      $all('.pages button').forEach((btn, index) => {
        btn.addEventListener('click', () => {
          currentIndex = index
          renderQuestion()
        })
      })
      // 提交按钮
      $('.submit').addEventListener('click', () => {
        // 计算未选择的题目数量
        const unfinishedQue = QuestionJosn.filter(v => !v.myAnswer).length
        if (unfinishedQue > 0) {
          if (confirm(`${unfinishedQue}道题目没有选择,确定提交吗？`)) {
            getTotal()
          }
        } else {
          getTotal()
        }
      })
      // 展开按钮
      $('.toggle').addEventListener('click', () => {
        $('.toggle').classList.toggle('close')
        if ($('.toggle').classList.contains('close')) {
          $('.pages').style.maxHeight = '0px'
        } else {
          $('.pages').style.maxHeight = '200px'
        }
      })
    }

    // 计算总分
    function getTotal() {
      const total = QuestionJosn.reduce((prev, val) => {
        // 遍历题目，判断选择的答案和标准答案是否一致
        const curNum = val.myAnswer?.toUpperCase() === val.questionAnswer.toUpperCase() ? 5 : 0
        return prev + curNum
      }, 0)
      alert(`总分:${total}`)

      const allInp = [...$all('.exam button'), ...$all('.exam input')]
      allInp.forEach(el => el.disabled = true)
    }

    // 选择选项
    function bindChange() {
      $all('.question input').forEach(inp => {
        inp.addEventListener('change', e => {
          // 存当前题目的答案
          QuestionJosn[currentIndex].myAnswer = e.target.value
          $all('.pages button')[currentIndex].classList.add('checked')
          console.log(QuestionJosn[currentIndex])
          // 计算进度
          const progress = QuestionJosn.filter(v => v.myAnswer).length / QuestionJosn.length * 100
          $('.line b').style.width = progress + '%'
          $('.line span').innerHTML = progress + '%'
        })
      })
    }



    // 倒计时
    class CountDown {
      constructor({ el, ms, onFinish, onStart, onStop }) {
        this.el = document.querySelector(el)
        this.ms = ms
        this.onFinish = onFinish
        this.onStart = onStart
        this.onStop = onStop
        this.isRunning = false
        this.el.innerHTML = this.format()
        this.start()
      }
      start() {
        this.isRunning = true
        this.onStart && this.onStart()
        this.timer = setInterval(() => {
          this.ms -= 1000
          this.el.innerHTML = this.format()
          if (this.ms === 0) {
            this.stop()
            // 倒计时结束通知用户
            this.onFinish && this.onFinish()
          }
        }, 1000)
      }

      stop() {
        this.isRunning = false
        clearInterval(this.timer)
        this.onStop && this.onStop()
      }

      format() {
        const h = this.addZero(Math.floor(this.ms / 1000 / 60 / 60))
        const m = this.addZero(Math.floor(this.ms / 1000 / 60 % 60))
        const s = this.addZero(Math.floor(this.ms / 1000 % 60))
        return `${h}:${m}:${s}`
      }
      addZero(n) {
        return n >= 10 ? n : '0' + n
      }
    }

    const myCount = new CountDown({
      el: '.count-down span',
      ms: 1000 * 5,
      onFinish: () => {
        console.log('倒计时结束')
        getTotal()
      },
      onStart: () => {
        console.log('开始了')
      },
      onStop: () => {
        console.log('暂停了')
      }
    })


    $('.timer-btn').innerHTML = myCount.isRunning ? '暂停' : '开始'
    $('.timer-btn').addEventListener('click', () => {
      if (myCount.isRunning) {
        myCount.stop()
        $('.timer-btn').innerHTML = '开始'
      } else {
        myCount.start()
        $('.timer-btn').innerHTML = '暂停'
      }
    })





    // const obj = {
    //   name: '小明'
    // }
    // obj.sex = false
    // // console.log(obj.name.toUpperCase())
    // // console.log(obj.sex && obj.sex.toUpperCase())
    // // 可选链: 
    // // 如果 obj.sex ！==  null 或者 undefined 就执行 toUpperCase(), 
    // console.log(obj.sex?.toUpperCase())



  </script>
</body>
</html>